<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">通用大数据框架智能计算引擎优化仿真平台</el-breadcrumb-item>
      <el-breadcrumb-item>计算任务</el-breadcrumb-item>
      <el-breadcrumb-item>计算创建</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query"  class="input-with-select" clearable @clear="getFileList" >
            <el-button slot="append" icon="el-icon-search" @click="getFileList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addOFilefromlocalVisble = true">上传文件</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary"  @click="createCalculation">创建计算</el-button>
        </el-col>
        <!--        <el-col :span="3">-->
        <!--          <el-button type="primary"  @click="startCalculation">开始计算</el-button>-->
        <!--        </el-col>-->
      </el-row>
      <el-table
          :data = "FileList.slice((queryInfo.pagenum-1)*queryInfo.pagesize,queryInfo.pagenum*queryInfo.pagesize)"
          border
          style="width: 100%">
        <el-table-column
            prop="foldername"
            label="计算名称"
            width="200">
        </el-table-column>
        <el-table-column
            prop="filename"
            label="文件名"
            width="200">
        </el-table-column>

        <el-table-column
            prop="createtime"
            label="创建时间"
            width="200">
        </el-table-column>
<!--        <el-table-column-->
<!--            prop="updateman"-->
<!--            label="上传人"-->
<!--            width="120">-->
<!--        </el-table-column>-->
        <el-table-column
            prop="size"
            label="所占大小"
            width="100">
        </el-table-column>
        <el-table-column
            prop="operate"
            label="操作"
            width="360">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="下载文件" placement="top">
              <!--              <el-button type="primary" icon="el-icon-download"  @click="fileDown(scope.row)"></el-button>-->
              <el-button type="primary" icon="el-icon-download"  @click="fileDown(scope.$index)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑文件" placement="top">
              <el-button type="primary" icon="el-icon-edit" @click="editFile(scope.row)" ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除dockers" placement="top">
              <el-button type="danger" icon="el-icon-delete" @click="removeOptimizeScheme(scope.row)"
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="SizeChange"
          @current-change="CurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[10,20,30]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="queryInfo.total">
      </el-pagination>

    </el-card>
    <el-dialog
        title="编辑文件"
        :visible.sync="editFileVisble"
        width="30%"
        @close="closeediFileDialog"
    >

      <el-form :model=" editFileParams"  :rules="editFileFormRul" ref="editFileParamsFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="计算名称" prop="filename" >
          <el-input v-model="editFileParams.tofoldername"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
     <el-button @click="editFileVisble= false">取 消</el-button>
     <el-button type="primary" @click="editFileList()">确 定</el-button>
     </span>
    </el-dialog>
    <!--上传数据-->
    <el-dialog
        title="从本地上传"
        :visible.sync="addOFilefromlocalVisble"
        width="30%"
        multiple = true
    >
      <el-upload
          drag
          :action="uploadfileurl"
          accept=".py"
          :on-success="successUpload"
          :on-error="errorUpload"
          multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip"></div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
     <el-button type="primary" @click="addOFilefromlocalVisble = false">完成</el-button>

     </span>
    </el-dialog>
    <!--    替换文件-->
    <el-dialog
        title="文件名重复，上传失败"
        :visible.sync="replacefileVisble"
        width="30%"
        :close-on-click-modal=false
        :close-on-press-escape=false
        :show-close=false
    >

      <el-button type="info" @click="replacefileVisble = false;deleteCache()">取消上传</el-button>
      <el-button type="primary" @click="replacefileVisble = false;replaceFile()">重写文件</el-button>

    </el-dialog>
    <!--    创建计算-->
    <el-dialog
        title="创建计算"
        :visible.sync="createCalculationVisble"
        width="20%"
        @open="calfilename();getoptimizeSchemeList()"
        @close="closecreateCalculationDialog"
    >
      <el-form :model="createCalculationForm" :rules="createCalculationFormRul" ref="createCalculationFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="计算名称" prop="calculationname">
          <el-input v-model="createCalculationForm.calculationname" @change="judgeFoldername"></el-input>
        </el-form-item>
        <el-form-item label="选择文件"   prop="checkedfile">
          <el-select v-model="createCalculationForm.checkedfile" placeholder="请选择" :filterable="true">
            <el-option
                v-for="item in files"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择容器" prop="calculationclassification">
          <el-select
              v-model="createCalculationForm.calculationclassification"
              placeholder="请选择"
              @change="selectcontainer()">
            <el-option
                v-for="item in calculationclassification"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                >
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
     <el-button @click="createCalculationVisble = false">取 消</el-button>
     <el-button type="primary" @click="createCalculationSubmit">确 定</el-button>
     </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  delete_cache_file,
  replace_upload_file,
  create_calculation,
  findAll_calculation_folder, findAll_python_filename, find_all_container, edit_foldername, delete_foldername,
  // download_result_file

} from "@/api/file";
import {state} from '@/store/modules/file.js';
import axios from "axios";
export default {
  data(){
    return{
      uploadfileurl: state().dataList[0].local_path+'/uploadFile/uploadcalculationFile',
      downfileurl: state().dataList[0].local_path+'/uploadFile/downloadCalResult',
      addFileVisble: false,
      addOFilefromlocalVisble:false,
      replacefileVisble: false,
      filename: [],
      foldername: [],
      ceshi: '',
      filenamecache: [],
      optimizeSchemeList:[],
      createCalculationForm:{
        calculationname:'',
        checkedfile: '',
        calculationclassification: '',
        namespace: ''
      },
      createCalculationFormRul:{
        calculationname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
        calculationclassification:[{ required: true, message: '请分类计算', trigger: 'blur' }],
        checkedfile:[{ required: true, message: '请选择文件', trigger: 'blur' }]
      },
      calculationclassification: [],
      files: [],
      editFileFormRul:{
        filename: [
          { required: true, message: '请输入文件名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      namespace: {
        container_namespace:'bigdata-platform',
      },
      FileList: [],
      editFileParams: {},
      editFileVisble:false,
      createCalculationVisble:false,
      queryInfo:{
        //查询参数
        query: '',
        pagenum: 1,
        pagesize: 10,
        total: 0
      },
    }
  },
  methods:{
    //更新页面
    getFileList(){
      console.log("query:   "+this.queryInfo.query)
      this.FileList= []
      let data = {"query":this.queryInfo.query}
      findAll_calculation_folder(data).then(res=>{
        console.log(res)
        for(let i=0;i<res.length;i++){
          this.FileList.push({
            foldername: res[i][0],
            filename: res[i][1],
            createtime: res[i][2],
            updateman: res[i][3],
            size: res[i][4]
          })
        }
        this.queryInfo.total=res.length
      }).catch(err=>{
        console.log(err)
        this.$message.error(err);
      })
    },
    //页面大小改变时触发
    SizeChange(newsize){
      this.queryInfo.pagesize = newsize
    },
    //当前页面改变时触发
    CurrentChange(newnumber){
      this.queryInfo.pagenum = newnumber
    },
    //上传文件---文件成功上传到后端返回
    successUpload(res){
      console.log(res)
      //文件名重复
      let arr=res.split(" ")
      console.log(arr[1])
      if(arr[1]=="repetition"){
        this.$message.warning("文件"+arr[0]+"重复")
        this.filenamecache.unshift(arr[0])
        this.replacefileVisble=true
      }
      else if(arr[1]=="success"){
        this.$message.success("上传数据成功")
        this.filename.unshift(arr[0])
      }
      else
        this.$message.error("上传数据失败")
    },
    //上传文件---上传失败返回
    errorUpload(err){
      console.log(err)
      this.$message.error("上传数据失败")
    },
    //上传文件---删除缓存文件
    deleteCache(){
      console.log("开始删除")
      for(let i=0;i<this.filenamecache.length;i++){
        let data = {"filename":this.filenamecache[i]}
        delete_cache_file(data).then(res=>{
          console.log(res)
          this.$message.success(res);
          // 逻辑处理
        }).catch(err=>{
          console.log(err)
          this.$message.error(err);
        })
      }
      this.filenamecache=[]
    },
    //上传文件---重写文件
    replaceFile() {
      console.log("开始重写")
      for(let i=0;i<this.filenamecache.length;i++){
        let data = {"filename":this.filenamecache[i]}
        replace_upload_file(data).then(res=>{
          console.log(res)
          this.$message.success(res+"重写成功")
          this.filename.unshift(res)
          // 逻辑处理
        }).catch(err=>{
          console.log(err)
          this.$message.error(err+"重写失败");
        })
      }
      this.filenamecache= []
    },
    // //开始计算
    // startCalculation(){
    //   console.log("这是测试计算")
    //   for (let i=0; i<this.filename.length; i++){
    //     console.log("开始执行"+this.filename[i])
    //     let data = {"calfileName":this.filename[i]}
    //     start_calculation_file(data).then(res=>{
    //       console.log("执行结果:"+res)
    //       this.$message.success("计算成功")
    //       // 逻辑处理
    //     }).catch(err=>{
    //       console.log(err)
    //       this.$message.error(err);
    //     })
    //   }
    //   this.filename=[]
    // },

    //     fileDown(row){
    //       var name = this.editFileParams.fileid;
    //       var url = row.path;
    //       const a = document.createElement('a')
    //       a.setAttribute('download', name)
    //       a.setAttribute('target', '_blank')
    //       a.setAttribute('href', "api"+url)
    //       a.click()
    // },
    fileDown(index){
      axios.get(this.downfileurl+'?newdirName='+this.FileList[index].foldername,
          {
            responseType: 'arraybuffer'
          }).then((res)=>{
        let fileName = this.FileList[index].foldername
        let fileURL = window.URL.createObjectURL(new Blob([res.data],{type: 'application/zip'}))
        let fileLink = document.createElement('a')
        fileLink.href = fileURL
        fileLink.setAttribute('download',fileName)
        document.body.appendChild(fileLink)
        fileLink.click()
              }).catch(()=>{
      })
    },
    //删除行记录
    removeOptimizeScheme(row){
      this.$confirm('此操作将永久删除'+row.foldername+', 是否继续?', '删除计算及结果', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {'foldername': row.foldername}
        delete_foldername(data).then((res)=>{
          console.log(res)
          this.$message.success('删除成功')
          this.getFileList()
        }).catch((err)=>{
          console.log(err)
          this.$message.error('删除失败')
        })
      }).catch(() => {

      });
    },
    //获取行信息
    editFile(row){
      console.log(row)
      this.editFileParams.foldername = row.foldername
      this.editFileVisble = true
    },
    //修改行
    editFileList(){
      edit_foldername(this.editFileParams).then(res=>{
        console.log(res)
        this.$message.success('计算名称修改成功')
        this.getFileList()
        this.editFileParams.tofoldername = ''
      }).catch(err=>{
        console.log(err)
        this.$message.error('计算名称修改失败')
      })
      this.editFileVisble = false
     },
    closeediFileDialog(){
      this.$refs.editFileParamsFormRef.resetFields()
    },
    closecreateCalculationDialog(){
      this.$refs.createCalculationFormRef.resetFields()

    },
    createCalculation(){
      this.$http.get('/').then(res=>{
        if(res.data.meta.status !== 200)
            // return this.$message.error('获取信息失败')

            //将这里的files等替换成数据库里的
          this.files=this.testfiles
        this.calculationclassification = this.testclassification

      })
      this.createCalculationVisble = true
    },
    //创建计算---判断计算名称是否重复
    judgeFoldername(){
      for(let i=0;i<this.FileList.length;i++){
        if(this.createCalculationForm.calculationname===this.FileList[i].foldername){
          this.$message.warning("计算名称已存在，请重新输入")
          this.createCalculationForm.calculationname= ''
        }}
    },
    //创建计算---获取可执行python文件名
    calfilename(){
      this.files=[]
      let data={"ceshi":this.ceshi}
      findAll_python_filename(data).then(res=>{
        console.log(res)
        for(let i=0;i<res.length;i++)
          this.files.push({
            value: res[i],
            lable: res[i]
          })
      }).catch(err=>{
        console.log(err)
      })
    },
    //创建计算---获取容器名
    getoptimizeSchemeList() {
      this.calculationclassification=[]
      find_all_container(this.namespace).then(res=>{
        this.optimizeSchemeList = res
        console.log("res    "+res)
          for(let i=0;i<res.length;i++)
            this.calculationclassification.push({
              value: res[i].container_name,
              lable: res[i].container_name
            })
      })
    },
    //创建计算--获取容器信息
    selectcontainer(){
      console.log("选择")
      this.optimizeSchemeList.forEach(index =>{
        if(index.container_name === this.createCalculationForm.calculationclassification){
          this.createCalculationForm.namespace = index.container_namespace
        }
      })
      console.log(this.createCalculationForm)
    },
    //创建计算
    createCalculationSubmit(){
      this.$refs.createCalculationFormRef.validate(valid=>{
        if(!valid)
          return alert('请输入正确信息')
        else {
          console.log("createCalculationForm")
          console.log(this.createCalculationForm)
          create_calculation(this.createCalculationForm).then(res=>{
            console.log(res)
            this.getFileList()
            this.$message.success("计算成功，点击下载按钮下载计算结果")
          }).catch(err=>{
            console.log(err)
          })
          this.createCalculationVisble = false
        }
      })
    },
  },
  created() {
    this.getFileList()
  }
}

</script>
<style>

</style>
